import React from 'react';

import {Dimensions, ImageBackground, Keyboard, LayoutAnimation, ScrollView, StatusBar, Text, View, Image, StyleSheet} from 'react-native';

import PropTypes from 'prop-types';
import PlatformTouchable from 'react-native-platform-touchable';
import Ionicons from 'react-native-vector-icons/Ionicons';
import ImagePicker from 'react-native-image-crop-picker';
import {ActionSheet, AlbumView, Overlay} from 'teaset';
import FadeImage from './FadeImage';
import CreateThumbnail from "../utils/CreateThumbnail";

const WIN_WIDTH = Dimensions.get('window').width;
const WIN_HEIGHT = Dimensions.get('window').height;


class ImageDisplayView extends React.Component {

    static propTypes = {
        image: PropTypes.object,
        imageStyle: PropTypes.object,
        onImageLongPress: PropTypes.func,
        onImagePress: PropTypes.func,
        editable: PropTypes.bool,
        mediaType: PropTypes.string,
        onImageDelete: PropTypes.func
    };

    constructor(props) {
        super(props);
        this.state = {image: props.image};
    }

    async componentDidMount() {
        // if (this.props.mediaType === 'video') {
        //     try {
        //         const {path} = await CreateThumbnail.createThumbnail({
        //             url: this.props.image.uri,
        //             timeStamp: 10000,
        //             type: this.props.image.uri.indexOf('http') >= 0 ? 'remote' : 'local'
        //         });
        //         this.setState({image: {uri: path}});
        //     } catch (e) {
        //         this.setState({image: {uri: ''}});
        //     }
        // }
    }

    render() {
        return <PlatformTouchable onPress={() => this.props.onImagePress()}
                                  onLongPress={() => this.props.onImageLongPress && this.props.onImageLongPress()}>
            <FadeImage
                style={{...this.props.imageStyle, alignItems: 'flex-end'}}
                source={this.state.image}
            >
                <View style={{position:'absolute', top:0, right:0, bottom:0, left:0, justifyContent:'center', alignItems:'center'}}>
                    {this.props.mediaType === 'video' ? <Image source={require('../images/icon_play.png')}/> : null}
                </View>
                {this.props.editable ?
                    <PlatformTouchable onPress={() => this.props.onImageDelete()} style={{
                        backgroundColor: '#FA8C1D',
                        borderRadius: 3,
                        paddingHorizontal: 5,
                        paddingVertical: 3,
                        position: 'absolute',
                        right: 0,
                        top: 0
                    }}><Ionicons name={'md-close'} size={10} color={'white'}/></PlatformTouchable> : null}

            </FadeImage>
        </PlatformTouchable>;
    }

}


export default class ImageHorizontalSelectView extends React.PureComponent {

    static propTypes = {
        height: PropTypes.number,
        images: PropTypes.array,
        onImageSelected: PropTypes.func,
        onImagePress: PropTypes.func,
        onImageLongPress: PropTypes.func,
        showAdd: PropTypes.bool,
        containerStyle: PropTypes.object,
        editable: PropTypes.bool,
        selectImageOption: PropTypes.func,
        hideWhenNoImage: PropTypes.bool,
        afterImageSelected: PropTypes.func,
        contentContainerStyle: PropTypes.object,
        mediaType: PropTypes.string,///video, image, any
        maxCount: PropTypes.number,
        maxFiles: PropTypes.number,
        multiple: PropTypes.bool,
        onImageDelete: PropTypes.func,
        justPicker: PropTypes.bool
    };

    static defaultProps = {
        height: 70,
        showAdd: true,
        editable: true,
        hideWhenNoImage: false,
        mediaType: 'photo',
        maxCount: 99,
        justPicker: false
    };

    constructor(props) {
        super(props);
        this.state = {images: props.images || []};
    }


    deleteImage = (index) => {
        this.state.images.splice(index, 1);
        const images = this.state.images.slice();
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        this.setState({images}, () => this.props.onImageDelete && this.props.onImageDelete(index));
    };

    clearImages() {
        this.setState({images: []});
    }

    selectImage = () => {
        Keyboard.dismiss();
        const options = {
            compressImageMaxWidth: 1000,
            compressImageMaxHeight: 1000,
            compressImageQuality: 0.7,
            compressVideoPreset: 'MediumQuality',
            mediaType: this.props.mediaType,
            multiple: this.props.multiple,
            maxFiles: this.props.maxFiles,
        };
        const another = this.props.selectImageOption ? this.props.selectImageOption(this.state.images.length) : {};
        if (this.props.justPicker) {
            ImagePicker.openPicker({...options, ...another, innerCamera: true}).then(image => {
                if (this.props.multiple) {
                    this.uploadImages(image);
                } else {
                    this.uploadImage(image.path);
                }

            });
        }
        else {
            let items = [
                {
                    title: this.props.mediaType === 'photo' ? '拍照' : (this.props.mediaType === 'video' ? '录像' : '相机'),
                    onPress: () => ImagePicker.openCamera({...options, ...another}).then(image => {
                        this.uploadImage(image.path);
                    }),
                },
                {
                    title: '从相册选择', onPress: () => ImagePicker.openPicker({...options, ...another}).then(image => {
                        if (this.props.multiple) {
                            this.uploadImages(image);
                        } else {
                            this.uploadImage(image.path);
                        }

                    }),
                },
            ];
            let cancelItem = {title: '取消'};
            ActionSheet.show(items, cancelItem);
        }

    };


    uploadImages = (images) => {
        if (this.props.onImageSelected) {
            if (images.length > 0) {
                const image = images.splice(0, 1)[0];
                this.props.onImageSelected(image.path, (imageUri) => {
                    this.state.images.push(imageUri);
                    const newImages = this.state.images.slice();
                    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
                    this.setState({images: newImages}, () => {
                        this.props.afterImageSelected && this.props.afterImageSelected(newImages);
                        this.uploadImages(images);
                    });
                }, (error) => {
                    this.uploadImages(images);
                });
            }
        } else {
            const newimages = this.state.images.concat(images.map(value => value.path));
            LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
            this.setState({newimages}, () => {
                this.props.afterImageSelected && this.props.afterImageSelected(newimages);
            });
        }
    };

    uploadImage = (image) => {
        if (this.props.onImageSelected) {
            this.props.onImageSelected(image, (imageUri) => {
                this.state.images.push(imageUri);
                const images = this.state.images.slice();
                LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
                this.setState({images}, () => {
                    this.props.afterImageSelected && this.props.afterImageSelected(images);
                });
            }, (error) => {

            });
        } else {
            this.state.images.push(image);
            const images = this.state.images.slice();
            LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
            this.setState({images}, () => {
                this.props.afterImageSelected && this.props.afterImageSelected(images);
            });
        }
    };

    images() {
        return this.state.images;
    }

    onImagePress(index) {
        let pressView = this.refs['it' + index];
        if (this.props.mediaType === 'photo') {
            requestAnimationFrame(() => {
                pressView.measure((x, y, width, height, pageX, pageY) => {
                    let overlayView = (
                        <Overlay.PopView
                            style={{}}
                            containerStyle={{flex: 1}}
                            overlayOpacity={1}
                            type='custom'
                            customBounds={{x: pageX, y: pageY, width, height}}
                            ref={v => this.fullImageView = v}
                        >
                            <AlbumView
                                style={{flex: 1}}
                                control={true}
                                images={this.state.images.map(value => {
                                    return <FadeImage defaultSource={null}
                                                      showLoading={true}
                                                      source={{uri: value}}
                                                      resizeMode={'contain'}
                                                      style={{width: WIN_WIDTH, height: WIN_HEIGHT}}
                                                      backgroundColor={'transparent'}/>;
                                })}
                                defaultIndex={index}
                                onPress={() => this.fullImageView && this.fullImageView.close()}
                            />
                            <StatusBar animated={false} hidden={true}/>
                        </Overlay.PopView>
                    );
                    Overlay.show(overlayView);
                });
            });
        }
        if (this.props.onImagePress){
            this.props.onImagePress(this.state.images[index], this.state.images, index, pressView);
        }
    }

    render() {
        const imageStyle = {width: this.props.height, height: this.props.height, borderRadius: 5, overflow: 'hidden'};
        if (!this.state.images) {
            return null;
        }
        if (this.state.images.length === 0 && this.props.hideWhenNoImage) {
            return null;
        }
        return <View style={[{height: this.props.height}, this.props.containerStyle]}><ScrollView
            style={{height: this.props.height}}
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            ref={scrollView => this.scrollView = scrollView}
            onContentSizeChange={() => {
                this.scrollView.scrollToEnd();
            }}
            contentContainerStyle={this.props.contentContainerStyle}
        >
            {this.state.images.map((value, index) => {
                let source = value;
                if (typeof (value) === 'string') {
                    source = {uri: value};
                }

                return <View style={{marginRight: 15}} key={value} ref={'it' + index}
                             renderToHardwareTextureAndroid={true}>

                    <ImageDisplayView editable={this.props.editable} image={source} imageStyle={imageStyle}
                                      mediaType={this.props.mediaType} onImageDelete={() => this.deleteImage(index)}
                                      onImageLongPress={() => this.props.onImageLongPress && this.props.onImageLongPress(index)}
                                      onImagePress={() => this.onImagePress(index)}/>
                </View>;
            })}
            {(this.props.showAdd && this.props.editable && (this.props.maxCount > 0 && this.state.images.length < this.props.maxCount)) ?
                <PlatformTouchable style={{marginRight: 15}} onPress={this.selectImage}>
                    <View style={{
                        ...imageStyle,
                        backgroundColor: '#aaa',
                        justifyContent: 'center',
                        alignItems: 'center',
                    }}>
                        <Ionicons name={'ios-add'} color={'white'} size={60}/>
                    </View>
                </PlatformTouchable> : null}
        </ScrollView></View>;
    }
}
